#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <strings.h>
#include <sys/errno.h>
#include <time.h>
#include <string.h>


int main(int argc, char * argv[])
{
  int listenfd, connfd;
  int ret;
  char buffer[1024];
  struct sockaddr_in sock;
  listenfd = socket(AF_INET, SOCK_STREAM, 0);
  if (0 > listenfd)
  {
    fprintf(stderr, "socket error, code=%d\n", errno);
    exit(-1);
  }
  bzero(&sock, sizeof(sock));
  sock.sin_family = AF_INET;
  sock.sin_port = htons(10000);
  sock.sin_addr.s_addr = htonl(INADDR_ANY);
  ret = bind(listenfd, reinterpret_cast<struct sockaddr *>(&sock), sizeof(sock));
  if (0 != ret)
  {
    fprintf(stderr, "bind error, code=%d\n", errno);
    exit(-1);
  }
  ret = listen(listenfd, 5);
  if (0 != ret)
  {
    fprintf(stderr, "listen error, code=%d\n", errno);
    exit(-1);
  }

  while(true)
  {
    connfd = accept(listenfd, reinterpret_cast<struct sockaddr *>(NULL), NULL);
    if (0 != ret)
    {
      fprintf(stderr, "accept failed, code=%d\n", errno);
      exit(-1);
    }
    time_t ticks = time(NULL);
    snprintf(buffer, sizeof(buffer), "%.24s\r\n", ctime(&ticks));
    printf("send buffer: %s\nbuffer len is%d\n", buffer, strlen(buffer));
    ret = write(connfd, buffer, strlen(buffer));
    if (-1 == ret)
    {
      fprintf(stderr, "wirte failed, code=%d\n", errno);
      exit(-1);
    }
    ret = close(connfd);
    if (0 != ret)
    {
      fprintf(stderr, "close connection failed, code=%d\n", errno);
      exit(-1);
    }
  }
  exit(0);
}
